//
//  JMTabBar.m
//  OpenSesame
//
//  Created by zhangjiaming on 15/12/21.
//  Copyright © 2015年 OpenSesame. All rights reserved.
//

#import "JMTabBar.h"
#import "JMTabBarButton.h"

@interface JMTabBar ()
@property (strong, nonatomic) NSMutableArray *tabBarButtons;
@property (weak, nonatomic) JMTabBarButton *selectedButton;
@end

@implementation JMTabBar
- (NSMutableArray *)tabBarButtons {
    if (!_tabBarButtons) {
        _tabBarButtons = [NSMutableArray array];
    }
    return _tabBarButtons;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

/**
 *  添加按钮
 *
 *  @param item 模型数据
 */
- (void)addTabBarButtonWithItem:(UITabBarItem *)item {
    // 创建按钮
    JMTabBarButton *button = [[JMTabBarButton alloc] init];
    
    // 传递模型数据
    button.item = item;
    
    // 添加按钮
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    [self addSubview:button];
    [self.tabBarButtons addObject:button];
}

/**
 *  监听tabBarButton的点击
 *
 *  @param button 被点击的tabBarButton
 */
- (void)buttonClick:(JMTabBarButton *)button {
    // 通知代理tabBarButton被点击了
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectButtonFrom:self.selectedButton.tag to:button.tag];
    }
    
    // 控制器选中按钮
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
}

/**
 *   布局子控件
 */
- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 3个按钮
    CGFloat buttonW = self.frame.size.width / 3;
    CGFloat buttonH = self.frame.size.height;
    for (int index = 0; index < self.tabBarButtons.count; index++) {
        JMTabBarButton *button = self.tabBarButtons[index];
        button.tag = index;
        CGFloat buttonX = buttonW * index;
        button.frame = CGRectMake(buttonX, 0, buttonW, buttonH);
        
        // 默认选中首页
        if (1 == index) {
            [self buttonClick:button];
        }
    }
}
@end
